package com.example.controller.admin;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.entity.CardInfo;
import com.example.entity.vo.CustomerCardVO;
import com.example.service.CardInfoService;
import com.example.service.CustomerCardService;
import com.example.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.List;

/**
 * 银行卡信息管理控制器
 */
@Controller
@RequestMapping("/admin/card")
public class CardInfoController {

    @Autowired
    private CardInfoService cardInfoService;
    
    @Autowired
    private CustomerCardService customerCardService;

    /**
     * 银行卡管理页面
     */
    @GetMapping("/page")
    public String cardPage() {
        return "admin/card/index";
    }

    /**
     * 获取银行卡列表
     */
    @GetMapping("/list")
    @ResponseBody
    public Result<Page<CustomerCardVO>> list(
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "limit", defaultValue = "10") Integer limit,
            @RequestParam(value = "keyword", required = false) String keyword) {
        
        Page<CustomerCardVO> pageParam = new Page<>(page, limit);
        LambdaQueryWrapper<CustomerCardVO> queryWrapper = new LambdaQueryWrapper<>();
        
        if (StringUtils.isNotBlank(keyword)) {
            queryWrapper.like(CustomerCardVO::getCardId, keyword)
                    .or()
                    .like(CustomerCardVO::getCustomerName, keyword);
        }
        
        Page<CustomerCardVO> pageResult = customerCardService.page(pageParam, queryWrapper);
        return Result.success(pageResult);
    }

    /**
     * 添加银行卡
     */
    @PostMapping("/add")
    @ResponseBody
    public Result<?> add(
            @RequestParam("customerId") String customerId,
            @RequestParam("savingId") Integer savingId,
            @RequestParam("password") String password) {
        
        CardInfo cardInfo = new CardInfo();
        // 生成16位随机卡号
        String cardId = "10103576" + String.format("%08d", (int)(Math.random() * 100000000));
        cardInfo.setCardId(cardId);
        cardInfo.setCustomerId(Integer.valueOf(customerId));
        cardInfo.setSavingId(savingId);
        cardInfo.setPass(password);
        cardInfo.setBalance(BigDecimal.valueOf(0.0)); // 初始余额为0
        cardInfo.setIsReportLoss("NO"); // 初始未挂失
        
        boolean saved = cardInfoService.save(cardInfo);
        if (saved) {
            return Result.success("添加成功，卡号为：" + cardId);
        } else {
            return Result.error("添加失败");
        }
    }

    /**
     * 修改银行卡
     */
    @PostMapping("/update")
    @ResponseBody
    public Result<?> update(@RequestBody CardInfo cardInfo) {
        boolean updated = cardInfoService.updateById(cardInfo);
        if (updated) {
            return Result.success("修改成功");
        } else {
            return Result.error("修改失败");
        }
    }

    /**
     * 删除银行卡
     */
    @DeleteMapping("/delete/{id}")
    @ResponseBody
    public Result<?> delete(@PathVariable("id") String id) {
        boolean removed = cardInfoService.removeById(id);
        if (removed) {
            return Result.success("删除成功");
        } else {
            return Result.error("删除失败");
        }
    }

    /**
     * 获取银行卡信息
     */
    @GetMapping("/info/{id}")
    @ResponseBody
    public Result<CardInfo> info(@PathVariable("id") String id) {
        CardInfo cardInfo = cardInfoService.getById(id);
        if (cardInfo != null) {
            return Result.success(cardInfo);
        } else {
            return Result.error("银行卡不存在");
        }
    }

    /**
     * 导出银行卡数据
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("银行卡信息", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        
        List<CustomerCardVO> list = customerCardService.list();
        EasyExcel.write(response.getOutputStream(), CustomerCardVO.class).sheet("银行卡信息").doWrite(list);
    }
} 